<template>
  <div>
    <r-search
      :searchForm="searchForm"
      :searchHandle="searchHandle"
      :searchData="searchData"
    />
    <div>
      <el-dialog
        width="35%"
        title="Distribution Agent Add Battery Swap Package"
        :visible.sync="dialogFormVisible"
      >
        <el-form style="display: flex;justify-content: center;">
          <el-form-item label="Agent" :label-width="formLabelWidth">
            <el-select
              placeholder="Please Select Agent"
              :clearable="true"
              v-model="agentValue"
              style="width:18.42rem"
            >
              <el-option
                v-for="item in agentArr"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <el-form style="display: flex;justify-content: center;">
          <el-form-item
            label="Battery Swap Package"
            :label-width="formLabelWidth"
          >
            <el-select
              placeholder="Please Select Battery Swap Package"
              :clearable="true"
              v-model="agentIdValue"
              multiple
              style="width:18.42rem"
            >
              <el-option
                v-for="item in agentIdArr"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="affirmAgentFn">Confirm</el-button>
        </div>
      </el-dialog>
    </div>
    <r-table
      :tableHandles="tableHandles"
      :isSelection="false"
      :isIndex="false"
      :isPagination="true"
      :tableData="tableData"
      :tableCols="tableCols"
      :tablePage="tablePage"
      :isHandle="true"
      @refresh="init()"
    >
    </r-table>
    <r-form
      :formRules="formRules"
      :formHandle="formHandle"
      :formData="formData"
      :formCols="formCols"
      ref="elForm"
      labelWidth="200px"
      dialogWidth="800px"
      :isHandle="true"
    />
  </div>
</template>
<script>
export default {
  data() {
    return {
      searchData: {
        btType: ""
      },
      searchForm: [
        {
          type: "select",
          prop: "btType",
          placeholder: "Battery Type",
          width: 230,
          options: [
            { label: "48V", value: "48" },
            { label: "60V", value: "60" },
            { label: "72V", value: "72" }
          ]
        }
        // {
        //   type: 'input',
        //   prop: 'name',
        //   placeholder: 'Replacement Count',
        //   width: 150
        // },
      ],
      searchHandle: [
        {
          label: "Search",
          type: "success",
          plain: true,
          icon: "el-icon-search",
          handle: e => this.init()
        }
      ],

      tableHandles: [
        {
          label: "Add Package",
          type: "primary",
          plain: true,
          handle: e => this.elFormVisible()
        },
        {
          label: "Distribution Agent Add Package",
          type: "primary",
          plain: true,
          handle: e => {
            this.dialogFormVisible = true;
          }
        }
      ],
      tableData: [{}],
      tableCols: [
        // {
        //   label: '序号',
        //   prop: 'name',
        // },
        {
          label: "Battery Swap Package Name",
          prop: "mealName"
        },
        {
          label: "Package Money",
          prop: "price",
          formatter: e => "$" + e.price
        },
        {
          label: "Valid Duration",
          prop: "days",
          formatter: e => e.days + "/day"
        },
        {
          label: "Replacement Count",
          prop: "num",
          formatter: e => (e.num === -1 ? "Unlimited" : e.num)
        },
        {
          label: "Battery Type",
          prop: "btType",
          formatter: e => e.btType + "V"
        },
        {
          label: "Update Time",
          prop: "ctime"
        },
        {
          label: "Enable Status",
          type: "switch",
          prop: "status",
          values: [1, 2],
          change: row => this.changestate(row)
        },

        {
          label: "Operations",
          type: "button",
          width: 300,
          btnList: [
            {
              label: "Edit",
              type: "primary",
              plain: true,
              handle: row => this.elFormDetail(row)
            },
            {
              label: "Delete",
              type: "danger",
              plain: true,
              handle: row => this.del(row)
            }
          ]
        }
      ],
      tablePage: { limit: 10, page: 1, total: 0 },
      formData: {
        mealName: "",
        days: "",
        btType: "",
        btTypeId: "",
        num: "",
        price: ""
      },
      formCols: [
        // {
        //   type: "select", label: "Package Name", width: 350, prop: "mealName", options: [
        //     { label: '60V月租', value: '60V月租' },
        //     { label: '测试', value: '测试' },
        //     { label: '30天', value: '30天' },
        //     { label: '20天', value: '20天' },
        //     { label: '15天', value: '15天' }
        //   ]
        // },
        { type: "input", label: "Package Name", width: 350, prop: "mealName" },
        // { type: "select", label: "PackageType", width: 350, prop: "name" },
        {
          type: "input",
          label: "Package Time(day)",
          width: 350,
          prop: "days"
          // remark: "天"
        },
        // { type: "select", label: "单位", width: 350, prop: "name" },
        {
          type: "select",
          label: "Battery Type",
          width: 350,
          prop: "btType",
          options: []
          // options: [
          //   { label: '48V', value: '48' },
          //   { label: '60V', value: '60' },
          //   { label: '72V', value: '72' },
          // ],
        },
        {
          type: "input",
          label: "Battery Swaps Rent Number",
          prop: "num",
          inputButton: true,
          width: 280,
          inputButtonFn: e => {
            this.formData.num = "Unlimited";
          }
        },
        {
          type: "input",
          label: "Package Money($)",
          width: 350,
          prop: "price"
          // remark: "元"
        }
      ],
      formRules: {
        mealName: [
          {
            required: true,
            message: "Please Input Package Name",
            trigger: "blur"
          }
        ],
        days: [
          {
            required: true,
            message: "Please Input Package Time",
            trigger: "blur"
          }
        ],
        btType: [
          {
            required: true,
            message: "Please Input Battery Type",
            trigger: "blur"
          }
        ],
        num: [
          {
            required: true,
            message: "Please Input Battery Swaps Rent Number",
            trigger: "blur"
          }
        ],
        price: [
          {
            required: true,
            message: "Please Input Package Money",
            trigger: "blur"
          }
        ]
      },
      formHandle: [
        {
          label: "Cancel",
          handle: e => this.elFormVisible()
        },
        {
          label: "Confirm",
          type: "success",
          handle: e => this.elFormSubmit()
        }
      ],
      agentArr: [],
      agentIdArr: [],
      dialogFormVisible: false,
      formLabelWidth: "160px",
      agentValue: "",
      agentIdValue: [],
      inquireAgentData: []
    };
  },
  components: {},
  computed: {},
  watch: {
    dialogFormVisible: {
      handler(newValue, oldValue) {
        if (!newValue && oldValue) {
          this.agentValue = "";
          this.agentIdValue = [];
        } else if (newValue && !oldValue) {
          this.agentValue = "";
          this.agentIdValue = [];
        }
      },
      deep: true // 深度监听
    },
    agentValue: {
      handler(newValue) {
        // console.log('新', newValue, '---旧', oldValue)
        if (newValue) {
          this.inquireAgentFn(newValue);
        } else {
          this.inquireAgentFn("");
        }
      },
      deep: true // 深度监听
    }
  },
  async mounted() {
    this.init();
    this.batteryTypeList();
    // 拿到Agentid列表
    let param = {
      pageNum: this.tablePage.page,
      pageSize: this.tablePage.limit
    };
    let res = await this.apis.agent_list(param);
    let arr = res.rows;
    arr.forEach(i => {
      let testAgentArr = {
        id: i.id,
        name: i.name
      };
      this.agentArr.push(testAgentArr);
    });
  },
  methods: {
    async inquireAgentFn(id) {
      this.agentIdValue = [];
      let res = await this.apis.mealExchangeGetAgentMealList(id);
      this.inquireAgentData = res.data || [];
      if (this.inquireAgentData) {
        this.inquireAgentData.forEach(i => {
          this.agentIdValue.push(i.id);
        });
      }
    },

    async affirmAgentFn() {
      if (this.agentValue) {
        // && this.agentIdValue.length !== 0
        let params = {
          agentId: this.agentValue,
          ids: this.agentIdValue || []
        };
        let res = await this.apis.webMealExchange(params);

        this.$message({
          type: res.code == 200 ? "success" : "error",
          message: res.msg
        });
        this.dialogFormVisible = false;
      } else {
        this.$message({
          type: "error",
          message: "Please Select Agent"
        });
        return false;
      }
    },
    async init() {
      let parm = {
        ...this.searchData,
        ...{
          pageNum: this.tablePage.page,
          pageSize: this.tablePage.limit
        }
      };
      let res = await this.apis.mealExchange_list(parm);
      if (res) {
        this.tableData = res.rows || [];
        this.tablePage.total = res.total;
        this.agentIdArr = [];
        // 拿到换电Package数组
        if (this.tableData) {
          this.tableData.forEach(i => {
            let testAgentArr = {
              id: i.id,
              name: i.mealName
            };
            this.agentIdArr.push(testAgentArr);
          });
        }
      }
    },

    async elFormSubmit() {
      this.$refs.elForm.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (this.formData.num === "Unlimited") {
            this.formData.num = -1;
          }

          if (this.formData.id) {
            const res = await this.apis.mealExchange_updata({
              ...this.formData
            });
          } else {
            this.formData.btTypeId = this.formData.btType.split(",")[0];
            this.formData.btType = this.formData.btType.split(",")[1];
            console.log(2222, this.formData);
            const res = await this.apis.mealExchange_save({ ...this.formData });
          }

          this.init();
          this.elFormVisible();
        }
      });
    },
    async changestate(row) {
      const res = await this.apis.mealExchange_updata({
        id: row.id,
        status: row.status
      });
      this.$message({
        message: "Operations Success！",
        type: "success"
      });
    },
    elFormDetail(row) {
      console.log(row);
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = row[key];
        this.formData.num = row.num === -1 ? "Unlimited" : row.num;
      });
      this.formData.id = row.id;
      this.elFormVisible();
    },
    del(row) {
      this.$confirm(`Delete Current Data`, "Hint", {
        confirmButtonText: "Confirm",
        cancelButtonText: "Cancel",
        type: "warning"
      }).then(async () => {
        const res = await this.apis.mealExchange_del({
          id: row.id
        });

        this.init();

        this.$message({
          message: "Operations Success！",
          type: "success"
        });
      });
    },
    async batteryTypeList() {
      const res = await this.apis.batteryTypeList({
        pageNum: 1,
        pageSize: 100
        // commonType: 1
      });
      let list = res.rows || [];
      let options = [];
      let options1 = [];
      // this.formCols.btType.options = []
      list.map(res => {
        options1.push({
          value: res.id + "," + res.typeName,
          label: res.typeName
        });
        options.push({
          value: res.id,
          label: res.typeName
        });
      });
      this.searchForm[
        this.labIndex2(this.searchForm, "btType")
      ].options = options;
      this.formCols[this.labIndex2(this.formCols, "btType")].options = options1;
    }
  }
};
</script>
<style scoped lang="scss">
.el-icon-search {
  margin-right: 10px;
}

.Tip {
  margin-left: 20px;
}
</style>
